import React, { useEffect, useState } from "react";
import { Button, Col, Form, Input, Flex, Row, Drawer, Radio, Select } from "antd";
import { DeleteOutlined } from '@ant-design/icons';
import { apiSysDictSelect } from '../../../../services/common';
import { apiMSDItemAdd, apiMSDItemView, apiMSDItemEdit } from '../../../../services/masterData/item';
import { transformArray, getUserName } from '../../../../utils/commonUtil';
import { useTranslation } from 'react-i18next';
import {
  SYSCODE,
  DROPDOWN,
  TEXTINPUT,
  NUMBERINPUT,
  TEXTAREA,
  CONFIG_ITEM_KEYS
} from '../../../../utils/constant';


const NewModal = (props) => {

  const [form] = Form.useForm();
  const { t } = useTranslation();
  const { TextArea } = Input;
  const username = getUserName();
  const [initialValues, setInitialValues] = useState();
  const [sysDictData, setSysDictData] = useState([]);
  const [buListData, setBuListData] = useState([]);
  const [radioValue, setRadioValue] = useState('');
  const { MODULE, BU, MD_ITEM_TYPE } = CONFIG_ITEM_KEYS;

  const {
    openDrawer,
    setOpenDrawer,
    editSucessFn,
    editType,
    recordData } = props;

  const apiSysDictSelectAynsc = () => {
    const params = {
      sysCode: SYSCODE,
      dictCodes: [MODULE, BU, MD_ITEM_TYPE]
    }
    apiSysDictSelect(params).then((res) => {
      if (res?.data) {
        setSysDictData(res?.data?.data);
      }
    });
  };

  // const apiBuSysDictSelectAynsc = ()=>{
  //     const params = {
  //         sysCode: SYSCODE,
  //         dictCode: 'bu'
  //     }
  //     apiSysDictSelect(params).then((res)=>{
  //         if(res?.data){
  //             const result = transformArray(res?.data?.data?.items);
  //             setBuListData(result);
  //         }
  //     });
  // };

  const initModalData = (viewData) => {
    let itemValue = '';
    let dropDownItems = [];
    if (viewData.itemType === TEXTINPUT) {
      itemValue = viewData.textTypeData;
    } else if (viewData.itemType === NUMBERINPUT) {
      itemValue = viewData.numericTypeData;
    } else if (viewData.itemType === TEXTAREA) {
      itemValue = viewData.textareaTypeData;
    } else if (viewData.itemType === DROPDOWN) {
      dropDownItems = viewData?.dropdownTypeData?.split(',');
    };
    const modalData = { ...viewData, itemValue, dropDownItems };
    setInitialValues(modalData);
  };

  const apiMSDItemViewAynsc = () => {
    const params = {
      id: recordData.itemMaintenanceId,
    }
    apiMSDItemView(params).then((res) => {
      if (res?.data) {
        const viewData = res?.data?.data?.item;
        initModalData(viewData);
        setRadioValue(viewData.itemType);
      }
    })
  }

  // new
  const apiMSDItemAddAynsc = (values) => {
    const params = {
      buType: values.buType,
      itemName: values.itemName?.trim(),
      itemType: values.itemType,
      moduleName: values.moduleName,
      dropdownTypeData: values.itemType === DROPDOWN ? values.dropDownItems?.join(',') : '',
      textTypeData: values.itemType === TEXTINPUT ? values.itemValue : '',
      numericTypeData: values.itemType === NUMBERINPUT ? values.itemValue : '',
      dateTypeData: '',
      attachmentTypeData: '',
      textareaTypeData: values.itemType === TEXTAREA ? values.itemValue : '',
      booleanTypeData: '',
      remark: values.remark || '',
      userId: username
    };
    apiMSDItemAdd(params).then((res) => {
      if (res?.data) {
        setOpenDrawer(false);
        editSucessFn();
      }
    })
  }

  // edit
  const apiMSDItemEditAynsc = (values) => {
    const params = {
      itemMaintenanceId: recordData.itemMaintenanceId,
      buType: values.buType,
      itemName: values.itemName,
      itemType: values.itemType,
      moduleName: values.moduleName,
      dropdownTypeData: values.itemType === DROPDOWN ? values.dropDownItems?.join(',') : '',
      textTypeData: values.itemType === TEXTINPUT ? values.itemValue : '',
      numericTypeData: values.itemType === NUMBERINPUT ? values.itemValue : '',
      dateTypeData: '',
      attachmentTypeData: '',
      textareaTypeData: values.itemType === TEXTAREA ? values.itemValue : '',
      booleanTypeData: '',
      remark: values.remark || '',
      userId: username
    };
    apiMSDItemEdit(params).then((res) => {
      if (res?.data) {
        setOpenDrawer(false);
        editSucessFn();
      }
    })
  }

  const onStatusChange = (e) => {
    setRadioValue(e.target.value);
  }

  const clickOKBtn = (values) => {
    if (editType === 'new') {
      apiMSDItemAddAynsc(values);
    } else if (editType === 'edit') {
      apiMSDItemEditAynsc(values);
    }
  }

  useEffect(() => {
    apiSysDictSelectAynsc();
    if (editType !== 'new') {
      apiMSDItemViewAynsc();
    } else {
      setInitialValues({ dropDownItems: [''] });
    }
  }, [])

  return (
    <Drawer
      title={t(`common.${editType}`)}
      width={520}
      onClose={() => setOpenDrawer(false)}
      open={openDrawer}>
      {initialValues && <Form form={form} initialValues={initialValues} disabled={editType === 'view'} onFinish={clickOKBtn} layout="vertical">
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item name="buType" label={t('common.bu')} rules={[
              {
                required: true,
                message: t('common.inputRequired'),
              }

            ]}>
              <Select disabled={editType === 'edit' || editType === 'view'} placeholder={t('common.pleaseSelect')} options={transformArray(sysDictData?.[BU])} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item name="moduleName" label={t('common.module')} rules={[
              {
                required: true,
                message: t('common.inputRequired'),
              }

            ]}>
              <Select disabled={editType === 'edit' || editType === 'view'} placeholder={t('common.pleaseSelect')} options={transformArray(sysDictData?.[MODULE])} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item name="itemName" label={t('common.itemName')} rules={[
              {
                required: true,
                message: t('common.inputRequired'),
              }

            ]}>
              <Input disabled={editType === 'edit' || editType === 'view'} placeholder={t('common.pleaseEnter')} allowClear />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item name="itemType" label={t('common.type')} rules={[
              {
                required: true,
                message: t('common.inputRequired'),
              }
            ]}>
              <Radio.Group disabled={editType === 'edit' || editType === 'view'} onChange={onStatusChange} value={radioValue}>
                {sysDictData?.[MD_ITEM_TYPE]?.map((item) => {
                  return (
                    <Radio value={item}>{item}</Radio>
                  )
                })}
              </Radio.Group>
            </Form.Item>
            {/* {
              (radioValue === NUMBERINPUT || radioValue === TEXTINPUT || radioValue === TEXTAREA) &&
              <Form.Item name="itemValue" label={t('common.value')}>
                <Input placeholder={t('common.pleaseEnter')} allowClear />
              </Form.Item>
            } */}
            {
              (radioValue == DROPDOWN) &&
              <Flex align="center">
                <div style={{ flex: 1, marginBottom: '6px' }}>{t('common.value')}</div>
              </Flex>
            }
            {radioValue == DROPDOWN && <Form.List name="dropDownItems">
              {(fields, { add, remove }) => (
                <div
                  className="itemTableClass"
                  style={{
                    marginBottom: '24px',
                    display: 'flex',
                    rowGap: 10,
                    flexDirection: 'column'
                  }}
                >
                  {fields.map((field) => (
                    <Flex>
                      <Form.Item label="" style={{ flex: 1, marginRight: '10px' }} name={[field.name]} rules={[{ required: true, message: t('common.inputRequired') }]}>
                        <Input placeholder={t('common.pleaseEnter')} />
                      </Form.Item>
                      <Button type="link" style={{ color: '#333', padding: '0' }} onClick={() => { remove(field.name); }}>
                        <DeleteOutlined />
                      </Button>
                    </Flex>
                  ))}

                  <Button type="primary" ghost style={{ width: "100px" }} onClick={() => add()} block>
                    {t('common.add')}
                  </Button>
                </div>
              )}
            </Form.List>}
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item name="remark" label={t('common.remarks')} >
              <TextArea placeholder={t('common.pleaseEnter')} allowClear />
            </Form.Item>
          </Col>
        </Row>

        <div style={{ display: 'flex', justifyContent: 'end', marginTop: '60px' }}>
          <Form.Item >
            <Button type="primary" htmlType="submit" >
              {t('save')}
            </Button>
          </Form.Item>

        </div>
      </Form>}

    </Drawer>
  )
};

export default NewModal;